package com.ruoyi.cfuser.service.impl;

import java.util.List;
import java.util.UUID;

import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.ParsedStats;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.cfuser.mapper.OrdersMapper;
import com.ruoyi.cfuser.api.domain.Orders;
import com.ruoyi.cfuser.service.IOrdersService;

import javax.annotation.Resource;

/**
 * 订单管理Service业务层处理
 *
 * @author feng
 * @date 2025-02-21
 */
@Service
public class OrdersServiceImpl implements IOrdersService {
    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ElasticsearchRestTemplate restTemplate;

    /**
     * 查询订单管理
     *
     * @param id 订单管理主键
     * @return 订单管理
     */
    @Override
    public Orders selectOrdersById(Long id) {
        return ordersMapper.selectOrdersById(id);
    }

    /**
     * 查询订单管理列表
     *
     * @param orders 订单管理
     * @return 订单管理
     */
    @Override
    public List<Orders> selectOrdersList(Orders orders) {
        //

        return ordersMapper.selectOrdersList(orders);
    }

    /**
     * ES查询所有商铺订单（花了钱的）
     *
     * @return 订单管理
     */
    @Override
    public List<Orders> selectOrdersListByStatusAll() {

        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //待完成--根据店铺分桶，根据日期使用聚合

//        第一层---category桶
        queryBuilder.addAggregation(AggregationBuilders.terms("shopAggs")
                .field("mid")//字段mid
//                子聚合    第三层---stats聚合方式根据price聚合
                .subAggregation(AggregationBuilders.stats("priceAggs")
                        .field("price")));

/*//        第一层---category桶
        queryBuilder.addAggregation(AggregationBuilders.terms("categoryAggs")
                .field("attr.category")//字段attr下面的字段category
//                子聚合    第二层---brand桶
                .subAggregation(AggregationBuilders.terms("brandAggs")
                        .field("attr.brand")
//                子聚合    第三层---stats聚合方式根据price聚合
                        .subAggregation(AggregationBuilders.stats("priceAggs")
                                .field("price"))));*/

        SearchHits<Orders> goods = restTemplate.search(queryBuilder.build(), Orders.class, IndexCoordinates.of("goods"));


        /**
         *  获取聚合结果：使用第一层聚合的桶名作为键  聚合结果作为值存到map中
         */
        Aggregations aggregations = (Aggregations) goods.getAggregations().aggregations();
        //获取第一层聚合的结果对象
        ParsedStringTerms orderAggs = aggregations.get("shopAggs");
        System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

        List<? extends Terms.Bucket> orderAggsBuckets = orderAggs.getBuckets();
        orderAggsBuckets.forEach(brandAggsBucket -> {
            System.out.println("key = " + brandAggsBucket.getKey());
            System.out.println("docCount = " + brandAggsBucket.getDocCount());

            ParsedStats priceAggs = (ParsedStats) brandAggsBucket.getAggregations().asMap().get("priceAggs");

            System.out.println("类型 = " + priceAggs.getType());
            System.out.println("平均值 = " + priceAggs.getAvg());
            System.out.println("总数 = " + priceAggs.getCount());
            System.out.println("最大值 = " + priceAggs.getMax());
            System.out.println("最小值 = " + priceAggs.getMin());
            System.out.println("和 = " + priceAggs.getSum());
        });
        return null;
    }

    /**
     * 新增订单管理
     *
     * @param orders 订单管理
     * @return 结果
     */
    @Override
    public int insertOrders(Orders orders) {
        orders.setVerificationCode(UUID.randomUUID().toString());
//         通过redis获取用户id
        Object o = redisTemplate.opsForValue().get("user:id");

        return ordersMapper.insertOrders(orders);
    }

    /**
     * 修改订单管理
     *
     * @param orders 订单管理
     * @return 结果
     */
    @Override
    public int updateOrders(Orders orders) {
        return ordersMapper.updateOrders(orders);
    }

    /**
     * 批量删除订单管理
     *
     * @param ids 需要删除的订单管理主键
     * @return 结果
     */
    @Override
    public int deleteOrdersByIds(Long[] ids) {
        return ordersMapper.deleteOrdersByIds(ids);
    }

    /**
     * 删除订单管理信息
     *
     * @param id 订单管理主键
     * @return 结果
     */
    @Override
    public int deleteOrdersById(Long id) {
        return ordersMapper.deleteOrdersById(id);
    }
}
